﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAL
{
    public class MovieData
    {
        //对于关于电影的数据操作类
        public IQueryable<Movies> Search(string Searchtext)
        {
            ProjectDBEntities sea = new ProjectDBEntities();
            IQueryable<Movies> a = from m in sea.Movies
                    where (m.actors == Searchtext || m.name==Searchtext || m.director==Searchtext)
                    select m;
            if (a != null && a.Count() > 0)
                return a;
            else
                return null;
        }
        public IQueryable<Movies> MessageData()
        {
            //创建上下文对象，用来操作数据库
            ProjectDBEntities pde = new ProjectDBEntities();
            //用linq语句查询出所有的电影
            var u = from c in pde.Movies
                    select c;
            return u;

        }
        public Movies Hot()
        {
            //  ////创建上下文对象，用来操作数据库
            ProjectDBEntities pde = new ProjectDBEntities();
            //查询电影评分表取出电影的id和对应电影所有评分的平均值存入list中
            var list = from c in pde.ScoresOfMovies
                       group c by c.m_id into g
                       orderby g.Key
                       select new
                       {
                           MovieId = g.FirstOrDefault().m_id,
                           AvgScore = (from s in pde.ScoresOfMovies
                                       where s.m_id == g.Key
                                       select s.score).Average()

                       };
            //声明int变量id存储电影id
            //声明int变量score存储电影平均分
            int id = 0;
            int score = 0;
            //遍历list，取出最打的平均分和其对应的电影id，分别放入id和score变量中
            foreach (var l in list)
            {
                if (l.AvgScore >= score)
                {
                    score = Convert.ToInt32(l.AvgScore);
                    id = Convert.ToInt32(l.MovieId);
                }
            }
            //查询数据库，在电影表查到对应评分最高的电影的对象
            var hot = from c in pde.Movies
                       where c.movie_id == id
                       select c;            
            if (id == 0)
            {
                 hot = from c in pde.Movies
                          select c;
            }
           
            //返回该对象
            foreach (Movies c in hot)
            {
                return c;
            }

            return null;
        }
        //显示对应电影电影函数
        public IQueryable<Movies> Smovie()
        {
            //  ////创建上下文对象，用来操作数据库
            ProjectDBEntities pde = new ProjectDBEntities();
            //在Movies中查询查询MovieLists表中对应的当前电影id的电影集合，返回该集合列表
            var m = from v in pde.Movies
                    select v;
            return m;
        }

    }
}
